#!/usr/bin/env python
# coding: utf-8

# In[1]:


import scipy.stats as sst
import numpy as np
import matplotlib.pylab as plt
import matplotlib.pyplot as plot
from matplotlib.widgets import Cursor
import csv
import math
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FormatStrFormatter
import matplotlib.colors as colors
import pandas as pd
import matplotlib.mlab as mlab
import seaborn as sns
from sklearn import linear_model
import matplotlib as mpl
from matplotlib import patheffects
import mpl_toolkits.axisartist.axislines as axislines
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
import seaborn 
font_set = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=12)
font_set1 = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=9)
font_set1_1 = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=9.001)
font_set1_2 = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=9.0001)
font_set3 = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=7)
font_set2 = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=6)
font_set4 = FontProperties(fname=r'C:\windows\fonts\simsun.ttc',size=8)


# In[40]:


#对升序序列找到对匹配val值最接近的点坐标
def index_fit(y, val):
    if val >= y[-1]:
        return len(y) - 1
    for i, yi in enumerate(y):
        if val >= yi and val <= y[i + 1]:
            if abs(val - yi) <= abs(val - y[ i + 1]):
                fit_index = i
            else:
                fit_index = i+1
            break
    return fit_index

#用于计算Lxx, Lyy
def laa(x):
    x_mean = np.mean(x)
    lxx = np.sum((x-x_mean)**2)
    return lxx

#用于计算Lxy
def lab(x,y):
    x_mean = np.mean(x)
    y_mean = np.mean(y)
    lxy = np.sum((x-x_mean)*(y-y_mean))
    return lxy

#一元线性回归模型
def polyfit_one(x, y, alpha):
    if len(set(x))==1:
        if len(set(y))==1:
            poly_val=[999999,999999]
            R=999999
            R2=999999
            pval=999999
            linear_test=999999
            poly_int=999999
            lxx=999999
            lyy=999999
            lxy=999999
            sigma_est=999999
            x_mean=999999
            y_mean=999999
            test_level=999999
            n=999999
        else:
            poly_val=[99999999,np.mean(x)]
            R=999999
            R2=999999
            pval=999999
            linear_test=999999
            poly_int=999999
            lxx=999999
            lyy=999999
            lxy=999999
            sigma_est=999999
            x_mean=999999
            y_mean=999999
            test_level=999999
            n=999999
    else:
        assert len(x) == len(y)
        n = len(x)
        assert n > 2
        lxx = laa(x)
        lyy = laa(y)
        lxy = lab(x, y)
        R = lxy/(np.sqrt(lxx) * np.sqrt(lyy))
        R2 = R*R   #计算相关系数与决定系数
        
        b_est = lxy/lxx  #计算b估计
        x_mean = np.mean(x)
        y_mean = np.mean(y)
        a_est = y_mean - b_est * x_mean   #计算a估计
        Qe = lyy - b_est * lxy
        sigma_est2=(np.sum((y-a_est-b_est*x)**2))/(n-2)

        sigma_est = np.sqrt(sigma_est2) #sigma估计
        
        test = np.abs(b_est * np.sqrt(lxx))/sigma_est
        test_level = sst.t.ppf(1 - alpha/2, df=n - 2)
        linear_test = test > test_level   #线性回归检验
        pval = sst.t.sf(test,n-2)*2#计算p值

        #a,b的置信区间
        b_int = [b_est - test_level * sigma_est / np.sqrt(lxx), b_est + test_level * sigma_est / np.sqrt(lxx)]
        a_int = [y_mean - b_int[1] * x_mean, y_mean - b_int[0] * x_mean]

        poly_int = (a_int, b_int)

        poly_val = (a_est, b_est)

    #返回回归模型相应参数
    test_val = {'R': R,
                'R2': R2,
                'Pvalue':pval,
                'linear_test': linear_test,
                'poly_int': poly_int,
                }
    process_val = {'lxx': lxx,
                   'lyy': lyy,
                   'lxy': lxy,
                   'sigma_est': sigma_est,
                   'x_mean': x_mean,
                   'y_mean': y_mean,
                   'test_level': test_level,
                   'ndim': n,
                   }
    return (poly_val, test_val, process_val)

#计算相应的预测区间
def confidence_interval(y0=None, *args, **kwargs):
    a_est, b_est = args
    sigma_est = kwargs['sigma_est']
    test_level= kwargs['test_level']
    lxx = kwargs['lxx']
    n = kwargs['ndim']
    x_mean = kwargs['x_mean']

    if isinstance(y0, (int, float, np.ndarray)):
        x0 = (y0 - a_est) / b_est
    elif isinstance(y0, (list, tuple)):
        y0 = np.array(y0)
        x0 = (y0 - a_est) / b_est
    else:
        return None

    conf_down = y0 - test_level * sigma_est * np.sqrt(1 + 1 / n + ((x0 - x_mean) ** 2 / lxx))
    conf_up = y0 + test_level * sigma_est * np.sqrt(1 + 1 / n + ((x0 - x_mean) ** 2 / lxx))

    confidence_interval = (conf_down, conf_up)
    return confidence_interval

def LinearRegression (x,y,alpha):
    poly_val,test_val, process_val = polyfit_one(x, y, alpha)
    ytick_down = -500
    ytick_up = 900#此处大于坐标轴最大值就行
    Y_test = np.linspace(ytick_down, ytick_up, 1000000) #从ticks上下限间取1000000个点
    X_test = (Y_test - poly_val[0]) / poly_val[1]#这些x_test和y_test组成的点在拟合线上
    X_12 = Y_test / (5.893*1.8099)#p=pe线，第一、二区界限
    X_34 = Y_test / (-5.893*1.8099)#p=-pe线，第三四区界限
    Y_down, Y_up = confidence_interval(Y_test, *poly_val, **process_val)#相应预测区间的y值

    regr1 = linear_model.LinearRegression()
    regr1.fit(X_test.reshape(-1,1),Y_up)
    d_up = regr1.intercept_
    regr2 = linear_model.LinearRegression()
    regr2.fit(X_test.reshape(-1,1),Y_down)
    d_down = regr2.intercept_
    return (d_up, d_down,Y_test,X_test,Y_up,Y_down,X_12, X_34)

def select(xy,hull,a,b):
    x=[]
    y=[]
    for i in range(a,b):
        x.append(xy[hull[i],0])
        y.append(xy[hull[i],1])
    return np.array(x),np.array(y)
def plotsca_tb(ax,tb_mean,x,y):
    for i in range(len(tb_mean)):
        if tb_mean[i]!=999999:
            if y==1:
                ax.scatter(x[i],tb_mean[i],s=5,c='r',marker='^',label='TB',alpha=0.7)
                y=0
            else:
                ax.scatter(x[i],tb_mean[i],s=5,c='r',marker='^',alpha=0.7)


def plotsca_E(ax,e_mean,x,y):
    for i in range(len(e_mean)):
        if e_mean[i]!=999999:
            if y==1:
                ax.scatter(x[i],e_mean[i],s=5,c='k',marker='o',label='E',alpha=0.7)
                y=0
            else:
                ax.scatter(x[i],e_mean[i],s=5,c='k',marker='o',alpha=0.7)
                

def panduan(tb_mean):
    z=0
    for i in range(len(tb_mean)):
        if tb_mean[i]==999999:
            z=z+1
    if z==len(tb_mean):
        return 0
    else:
        return 1
    
def tuli(y):
    x=[0,0,0,0]
    for i in range(len(y)):
        if y[i]==1:
            x[i]=1
            break
    return x          


# In[41]:


#从csv文件里面读取x,y
def read_xy(file_path):
    with open(file_path,encoding="gbk") as fp:
        csv_reader = csv.reader(fp)
        x = []
        y = []
        check = []
        p_pe=[]
        p1_pe1=[]
        p2_pe2=[]
        p3_pe3=[]
        p4_pe4=[]
        p5_pe5=[]
        p6_pe6=[]
        p7_pe7=[]
        p8_pe8=[]
        p9_pe9=[]
        p10_pe10=[]
        p11_pe11=[]
        p12_pe12=[]
        dem=[]
        p=[]
        pe=[]
        tp_year=[]
        for ri,row in enumerate(csv_reader):
            if ri == 0:
                continue
            x.append(float(row[3]))#tb
            y.append(float(row[4]))#E
            p_pe.append(float(row[5]))#tb
            p1_pe1.append(float(row[6]))#tb
            p2_pe2.append(float(row[7]))#tb
            p3_pe3.append(float(row[8]))#tb
            p4_pe4.append(float(row[9]))#tb
            p5_pe5.append(float(row[10]))#tb
            p6_pe6.append(float(row[11]))#tb
            p7_pe7.append(float(row[12]))#tb
            p8_pe8.append(float(row[13]))#tb
            p9_pe9.append(float(row[14]))#tb
            p10_pe10.append(float(row[15]))#tb
            p11_pe11.append(float(row[16]))#tb
            p12_pe12.append(float(row[17]))#tb
            p.append(float(row[20]))#tb
            pe.append(float(row[21]))#tb
            dem.append(float(row[22]))#tb
            tp_year.append(float(row[23]))#tb
            check.append(float(row[1]))#value
        total=int(float(row[26]))
#             x = [round(i,5) for i in x]
#             y = [round(i,5) for i in y]
            
    return np.array(x), np.array(y), np.array(check),np.array(p_pe),np.array(p1_pe1),np.array(p2_pe2),np.array(p3_pe3),np.array(p4_pe4),np.array(p5_pe5),np.array(p6_pe6),np.array(p7_pe7),np.array(p8_pe8),np.array(p9_pe9),np.array(p10_pe10),np.array(p11_pe11),np.array(p12_pe12),total,np.array(p),np.array(pe),np.array(dem),np.array(tp_year)


# In[42]:


def data_process(x,y,alpha):
    n=total
#Holdridge温度体系求占比
    reserve_k_1 = []
    reserve_k_2 = []
    reserve_k_3 = []
    reserve_k_4 = []
    reserve_k_5 = []
    reserve_k_6 = []
    reserve_k_7 = []
    for k, x[k] in enumerate(x):
        if 0 <= x[k] < 1.5:#极地带
            reserve_k_1.append(k)
        elif 1.5 <= x[k] < 3:#亚极地带
            reserve_k_2.append(k)
        elif 3 <= x[k] < 6:#寒温带
            reserve_k_3.append(k)
        elif 6 <= x[k] < 10:#温带
            reserve_k_4.append(k)
        elif 10 <= x[k] < 14:#暖温带
            reserve_k_5.append(k)
        elif 14 <= x[k] < 22:#亚热带
            reserve_k_6.append(k)    
        else:#热带
            reserve_k_7.append(k) 

    TB_max = max(x)
    TB_min = min(x)
    TB_mean = np.mean(x)
    TB_std = np.std(x)
    TB_mean_plus_std = TB_mean + TB_std
    TB_mean_minus_std = TB_mean - TB_std
    E_max = max(y)
    E_min = min(y)
    E_mean = np.mean(y)
    E_std = np.std(y)
    E_mean_plus_std = E_mean + E_std
    E_mean_minus_std = E_mean - E_std       
    center = (TB_mean,E_mean)#中心点位置坐标 
    
    DEM_max = max(dem)
    DEM_min = min(dem)
    DEM_mean = np.mean(dem)
    DEM_std = np.std(dem)
    DEM_mean_plus_std = DEM_mean + DEM_std
    DEM_mean_minus_std = DEM_mean - DEM_std

    p_max = max(p)
    p_min = min(p)
    p_mean = np.mean(p)
    p_std = np.std(p)
    p_mean_plus_std = p_mean + p_std
    p_mean_minus_std = p_mean - p_std
    
    pe_max = max(pe)
    pe_min = min(pe)
    pe_mean = np.mean(pe)
    pe_std = np.std(pe)
    pe_mean_plus_std = pe_mean + pe_std
    pe_mean_minus_std = pe_mean - pe_std
    
    tp_year_max = max(tp_year)
    tp_year_min = min(tp_year)
    tp_year_mean = np.mean(tp_year)
    tp_year_std = np.std(tp_year)
    tp_year_mean_plus_std = tp_year_mean + tp_year_std
    tp_year_mean_minus_std = tp_year_mean - tp_year_std
#开始分区
    reserve_j_1 = []
    reserve_j_2 = []
    reserve_j_3 = []
    reserve_j_4 = []
    for j, xj in enumerate(x):#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列，同时列出数据和数据下标，一般用在 for 循环当中。
        if y[j] >= (5.893*1.8099) * x[j]:#第一区
#             y[j] = '%0.5f'% y[j]
            reserve_j_1.append(j)
        elif 0 <= y[j]  < (5.893*1.8099) * x[j]:#第二区
            reserve_j_2.append(j)
        elif (-5.893*1.8099) * x[j] < y[j] < 0:#第三区
            reserve_j_3.append(j)
        else:#第四区
            reserve_j_4.append(j) 

#第一区                
    tb1 = x[reserve_j_1].tolist()#转成列表
    E1 = y[reserve_j_1].tolist()  
    n1 = len(reserve_j_1)
    ratio1 = n1/n
    total_1=n1/total
#     print(p_pe[reserve_j_1].tolist())
#对第一区内的点分成12个月均大于p>=pe和 12个月中存在小于p<pe
    x1 = x[reserve_j_1]
    y1 = y[reserve_j_1]
    p_pe_1 = p_pe[reserve_j_1].tolist()
    p1_pe1_1 = p1_pe1[reserve_j_1].tolist()
    p2_pe2_1 = p2_pe2[reserve_j_1].tolist()
    p3_pe3_1 = p3_pe3[reserve_j_1].tolist()
    p4_pe4_1 = p4_pe4[reserve_j_1].tolist()
    p5_pe5_1 = p5_pe5[reserve_j_1].tolist()
    p6_pe6_1 = p6_pe6[reserve_j_1].tolist()
    p7_pe7_1 = p7_pe7[reserve_j_1].tolist()
    p8_pe8_1 = p8_pe8[reserve_j_1].tolist()
    p9_pe9_1 = p9_pe9[reserve_j_1].tolist()
    p10_pe10_1 = p10_pe10[reserve_j_1].tolist()
    p11_pe11_1 = p11_pe11[reserve_j_1].tolist()
    p12_pe12_1 = p12_pe12[reserve_j_1].tolist()
    reserve_j_1_1 = []
    reserve_j_1_2 = []
    j=[]
    for j,xj in enumerate(x1):
        if p1_pe1_1[j]>=0 and p2_pe2_1[j]>=0 and p3_pe3_1[j]>=0 and p4_pe4_1[j]>=0 and p5_pe5_1[j]>=0 and p6_pe6_1[j]>=0 and p7_pe7_1[j]>=0 and p8_pe8_1[j]>=0 and p9_pe9_1[j]>=0 and p10_pe10_1[j]>=0 and p11_pe11_1[j]>=0 and p12_pe12_1[j]>=0:
            reserve_j_1_1.append(j)
        else:
            reserve_j_1_2.append(j) 
    n1_1 = len(reserve_j_1_1)
    n1_2 = len(reserve_j_1_2)
    ratio1_1 = n1_1/n
    ratio1_2 = n1_2/n
    total1_1 = n1_1/total
    total1_2 = n1_2/total
    tb1_1 = x1[reserve_j_1_1].tolist()
    E1_1 = y1[reserve_j_1_1].tolist()
    tb1_2 = x1[reserve_j_1_2].tolist()
    E1_2 = y1[reserve_j_1_2].tolist()
        
    if n1_1>0:
        TB1_1_mean=np.mean(tb1_1)
        E1_1_mean=np.mean(E1_1)
        TB1_1_max=max(tb1_1)
        E1_1_max=max(E1_1)
        TB1_1_min=min(tb1_1)
        E1_1_min=min(E1_1)
    else:
        TB1_1_mean=999999
        E1_1_mean=999999
        TB1_1_max=999999
        E1_1_max=999999
        TB1_1_min=999999
        E1_1_min=999999
    if n1_2>0:
        TB1_2_mean=np.mean(tb1_2)
        E1_2_mean=np.mean(E1_2)
        TB1_2_max=max(tb1_2)
        E1_2_max=max(E1_2)
        TB1_2_min=min(tb1_2)
        E1_2_min=min(E1_2)
    else:
        TB1_2_mean=999999
        E1_2_mean=999999
        TB1_2_max=999999
        E1_2_max=999999
        TB1_2_min=999999
        E1_2_min=999999
#计算第一区TB,E的最大值，最小值，均值，标准差，均值+标准差，均值-标准差 
    if n1 > 0:
        TB_1_max = max(tb1)
        TB_1_min = min(tb1)
        TB_1_mean = np.mean(tb1)
        TB_1_std = np.std(tb1)
        TB_1_mean_plus_std = TB_1_mean + TB_1_std
        TB_1_mean_minus_std = TB_1_mean - TB_1_std
        E_1_max = max(E1)
        E_1_min = min(E1)
        E_1_mean = np.mean(E1)
        E_1_std = np.std(E1)
        E_1_mean_plus_std = E_1_mean + E_1_std
        E_1_mean_minus_std = E_1_mean - E_1_std
    else:
        E_1_mean=999999
        E_1_std=999999
        E_1_max=999999
        E_1_min=999999
        E_1_mean_plus_std=999999
        E_1_mean_minus_std=999999
        TB_1_mean=999999
        TB_1_std=999999
        TB_1_max=999999
        TB_1_min=999999
        TB_1_mean_plus_std=999999
        TB_1_mean_minus_std=999999

    tb2 = x[reserve_j_2].tolist()#转成列表
    E2 = y[reserve_j_2].tolist()
    n2 = len(reserve_j_2)
    ratio2 = n2/n
    total_2=n2/total
#计算第二区TB,E的最大值，最小值，均值，标准差，均值+标准差，均值-标准差       
    if n2 > 0:
        TB_2_max = max(tb2)
        TB_2_min = min(tb2)
        TB_2_mean = np.mean(tb2)
        TB_2_std = np.std(tb2)
        TB_2_mean_plus_std = TB_2_mean + TB_2_std
        TB_2_mean_minus_std = TB_2_mean - TB_2_std
        E_2_max = max(E2)
        E_2_min = min(E2)
        E_2_mean = np.mean(E2)
        E_2_std = np.std(E2)
        E_2_mean_plus_std = E_2_mean + E_2_std
        E_2_mean_minus_std = E_2_mean - E_2_std
    else:
        E_2_mean=999999
        E_2_std=999999
        E_2_max=999999
        E_2_min=999999
        E_2_mean_plus_std=999999
        E_2_mean_minus_std=999999
        TB_2_mean=999999
        TB_2_std=999999
        TB_2_max=999999
        TB_2_min=999999
        TB_2_mean_plus_std=999999
        TB_2_mean_minus_std=999999 
#     print('第二区：%d'%n2)
    tb3 = x[reserve_j_3].tolist()#转成列表
    E3 = y[reserve_j_3].tolist()
    n3 = len(reserve_j_3)
    ratio3 = n3/n
    total_3=n3/total
#计算第三区TB,E的最大值，最小值，均值，标准差，均值+标准差，均值-标准差    
    if n3 > 0:
        TB_3_max = max(tb3)
        TB_3_min = min(tb3)
        TB_3_mean = np.mean(tb3)
        TB_3_std = np.std(tb3)
        TB_3_mean_plus_std = TB_3_mean + TB_3_std
        TB_3_mean_minus_std = TB_3_mean - TB_3_std
        E_3_max = max(E3)
        E_3_min = min(E3)
        E_3_mean = np.mean(E3)
        E_3_std = np.std(E3)
        E_3_mean_plus_std = E_3_mean + E_3_std
        E_3_mean_minus_std = E_3_mean - E_3_std
    else:
        E_3_mean=999999
        E_3_std=999999
        E_3_max=999999
        E_3_min=999999
        E_3_mean_plus_std=999999
        E_3_mean_minus_std=999999
        TB_3_mean=999999
        TB_3_std=999999
        TB_3_max=999999
        TB_3_min=999999
        TB_3_mean_plus_std=999999
        TB_3_mean_minus_std=999999
#     print('第三区：%d'%n3)
    tb4 = x[reserve_j_4].tolist()#转成列表
    E4 = y[reserve_j_4].tolist()
    n4 = len(reserve_j_4)
    ratio4 = n4/n
    total_4=n4/total

#计算第四区TB,AET,OOV的最大值，最小值，均值，标准差，均值+标准差，均值-标准差  
    if n4 > 0:
        TB_4_max = max(tb4)
        TB_4_min = min(tb4)
        TB_4_mean = np.mean(tb4)
        TB_4_std = np.std(tb4)
        TB_4_mean_plus_std = TB_4_mean + TB_4_std
        TB_4_mean_minus_std = TB_4_mean - TB_4_std
        E_4_max = max(E4)
        E_4_min = min(E4)
        E_4_mean = np.mean(E4)
        E_4_std = np.std(E4)
        E_4_mean_plus_std = E_4_mean + E_4_std
        E_4_mean_minus_std = E_4_mean - E_4_std
    else:
        E_4_mean=999999
        E_4_std=999999
        E_4_max=999999
        E_4_min=999999
        E_4_mean_plus_std=999999
        E_4_mean_minus_std=999999
        TB_4_mean=999999
        TB_4_std=999999
        TB_4_max=999999
        TB_4_min=999999
        TB_4_mean_plus_std=999999
        TB_4_mean_minus_std=999999

    tb_234=tb2+tb3+tb4
    E_234=E2+E3+E4
    n_check=n1+n2+n3+n4
    

    all_value = {'n':n,'n_check':n_check,
#                  '回归方程':"E = %.2f *TB  + %.2f" % (poly_val[1], poly_val[0]),'R2':R2,'P':P,
#                 '拟合线斜率':poly_val[1],'拟合线截距':poly_val[0],
#                  '95%置信上限截距':d_up,'95%置信下限截距':d_down,
                'E_mean':E_mean,'E_std':E_std,'E_max':E_max,'E_min':E_min,'E_mean_plus_std':E_mean_plus_std,'E_mean_minus_std':E_mean_minus_std,
                'TB_mean':TB_mean,'TB_std':TB_std,'TB_max':TB_max,'TB_min':TB_min,'TB_mean_plus_std':TB_mean_plus_std,'TB_mean_minus_std':TB_mean_minus_std,
                'E_1_mean':E_1_mean,'E_1_std':E_1_std,'E_1_max':E_1_max,'E_1_min':E_1_min,'E_1_mean_plus_std':E_1_mean_plus_std,'E_1_mean_minus_std':E_1_mean_minus_std,
                'TB_1_mean':TB_1_mean,'TB_1_std':TB_1_std,'TB_1_max':TB_1_max,'TB_1_min':TB_1_min,'TB_1_mean_plus_std':TB_1_mean_plus_std,'TB_1_mean_minus_std':TB_1_mean_minus_std,
                'n1':n1,'ratio1':ratio1,
                'E_2_mean':E_2_mean,'E_2_std':E_2_std,'E_2_max':E_2_max,'E_2_min':E_2_min,'E_2_mean_plus_std':E_2_mean_plus_std,'E_2_mean_minus_std':E_2_mean_minus_std,
                'TB_2_mean':TB_2_mean,'TB_2_std':TB_2_std,'TB_2_max':TB_2_max,'TB_2_min':TB_2_min,'TB_2_mean_plus_std':TB_2_mean_plus_std,'TB_2_mean_minus_std':TB_2_mean_minus_std,
                'n2':n2,'ratio2':ratio2,
                'E_3_mean':E_3_mean,'E_3_std':E_3_std,'E_3_max':E_3_max,'E_3_min':E_3_min,'E_3_mean_plus_std':E_3_mean_plus_std,'E_3_mean_minus_std':E_3_mean_minus_std,
                'TB_3_mean':TB_3_mean,'TB_3_std':TB_3_std,'TB_3_max':TB_3_max,'TB_3_min':TB_3_min,'TB_3_mean_plus_std':TB_3_mean_plus_std,'TB_3_mean_minus_std':TB_3_mean_minus_std,
                'n3':n3,'ratio3':ratio3,
                'E_4_mean':E_4_mean,'E_4_std':E_4_std,'E_4_max':E_4_max,'E_4_min':E_4_min,'E_4_mean_plus_std':E_4_mean_plus_std,'E_4_mean_minus_std':E_4_mean_minus_std,
                'TB_4_mean':TB_4_mean,'TB_4_std':TB_4_std,'TB_4_max':TB_4_max,'TB_4_min':TB_4_min,'TB_4_mean_plus_std':TB_4_mean_plus_std,'TB_4_mean_minus_std':TB_4_mean_minus_std,
                'n4':n4,'ratio4':ratio4,
                'tb1':tb1,'tb2':tb2,'tb3':tb3,'tb4':tb4,
                 'E1':E1,'E2':E2,'E3':E3,'E4':E4,'tb_234':tb_234,'E_234':E_234,
                'ratio1_1':ratio1_1,'ratio1_2':ratio1_2,
                 'TB1_1_mean':TB1_1_mean,'TB1_2_mean':TB1_2_mean,'E1_1_mean':E1_1_mean,'E1_2_mean':E1_2_mean,
                 'TB1_1_max':TB1_1_max,'TB1_2_max':TB1_2_max,'E1_1_max':E1_1_max,'E1_2_max':E1_2_max,
                 'TB1_1_min':TB1_1_min,'TB1_2_min':TB1_2_min,'E1_1_min':E1_1_min,'E1_2_min':E1_2_min,
                'total1_1': total1_1,'total1_2': total1_2,'total_2': total_2,'total_3': total_3,
                'p_mean':p_mean,'p_std':p_std,'p_max':p_max,'p_min':p_min,
                'pe_mean':pe_mean,'pe_std':pe_std,'pe_max':pe_max,'pe_min':pe_min,
                'DEM_mean':DEM_mean,'DEM_std':DEM_std,'DEM_max':DEM_max,'DEM_min':DEM_min,
                'tp_year_mean':tp_year_mean,'tp_year_std':tp_year_std,'tp_year_max':tp_year_max,'tp_year_min':tp_year_min}
    return all_value


# In[43]:


#画左上角条形折线图函数
def barline1(all_value0,all_value1,fig):
#画柱形图  
    axins = fig.add_axes([0.15,0.71,0.25,0.165])
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False 
    x=[ 0.5, 1.1 ,1.7,  2.3]
    height=[all_value1['total1_1']*100,all_value1['total1_2']*100,all_value1['total_2']*100,all_value1['total_3']*100]
#     x1=[1]
#     x2=[1.6]
#     x3=[2.2]
#     x4=[2.8]
    x1=[0.5]
    x2=[1.1]
    x3=[1.7]
    x4=[2.3]
    zone1=['Ⅰ','Ⅱ','Ⅲ','Ⅳ']
    patches = axins.bar(x,height, width= 0.2,tick_label=zone1,facecolor='w',edgecolor='k')
    axins.set_ylim(0,100)
    axins.set_xlim(0,3)
    plt.xticks(fontproperties=font_set1_1)
    for rect in patches:
        height = rect.get_height()
        if height>0:
            axins.text(rect.get_x() + rect.get_width() / 2, height, str('%.2f'%height)+'%', ha='center', va='bottom',fontproperties =font_set3)
#TB轴    
    axins1=axins.twinx()
    tb1_mean=[all_value1['TB1_1_mean']]
    tb2_mean=[all_value1['TB1_2_mean']]
    tb3_mean=[all_value1['TB_2_mean']]
    tb4_mean=[all_value1['TB_3_mean']]
    tb1_max=[all_value1['TB1_1_max']]
    tb2_max=[all_value1['TB1_2_max']]
    tb3_max=[all_value1['TB_2_max']]
    tb4_max=[all_value1['TB_3_max']]
    tb1_min=[all_value1['TB1_1_min']]
    tb2_min=[all_value1['TB1_2_min']]
    tb3_min=[all_value1['TB_2_min']]
    tb4_min=[all_value1['TB_3_min']]
    y=[panduan(tb1_mean),panduan(tb2_mean),panduan(tb3_mean),panduan(tb4_mean)]
    y=tuli(y)
    plotsca_tb(axins1,tb1_mean,x1,y[0])
    plotsca_tb(axins1,tb1_max,x1,0)
    plotsca_tb(axins1,tb1_min,x1,0)
    plotsca_tb(axins1,tb2_mean,x2,y[1])
    plotsca_tb(axins1,tb2_max,x2,0)
    plotsca_tb(axins1,tb2_min,x2,0)
    plotsca_tb(axins1,tb3_mean,x3,y[2])
    plotsca_tb(axins1,tb3_max,x3,0)
    plotsca_tb(axins1,tb3_min,x3,0)
    plotsca_tb(axins1,tb4_mean,x4,y[3])
    plotsca_tb(axins1,tb4_max,x4,0)
    plotsca_tb(axins1,tb4_min,x4,0) 
    axins1.set_ylabel('TB (℃)',fontproperties =font_set1)
    
    TB_min=[all_value1['TB1_1_min'],
            all_value1['TB1_2_min'],
            all_value1['TB_2_min'],
            all_value1['TB_3_min']] 
    axins1_min=[]
    for i in range(0,len(TB_min)):
        if TB_min[i]!=999999:
            axins1_min.append(TB_min[i])
    axins1_min=min(axins1_min)    
    TB_max=[all_value1['TB1_1_max'],
            all_value1['TB1_2_max'],
            all_value1['TB_2_max'],
            all_value1['TB_3_max']]
    axins1_max=[]
    for i in range(0,len(TB_max)):
        if TB_max[i]!=999999:
            axins1_max.append(TB_max[i])
    axins1_max=max(axins1_max)

    
    ymajorLocator = MultipleLocator(5)
    ymajorFormatter = FormatStrFormatter('%d')
    axins1.yaxis.set_major_locator(ymajorLocator)
    axins1.yaxis.set_major_formatter(ymajorFormatter)
    axins1.set_ylim(0,30)        
#画温度带
    xzone=[2.61,2.77,2.77,2.77,2.77,2.77,2.85]
    yzone=[0.2,1.7,4,7.3,11.3,17,22.5]
    zone=['高山极地带', '苔原带', '寒温带', '中温带', '暖温带', '亚热带', '热带']
    line=[0,1.5,3,6,10,14,22,30]
    t1={}
    t2={}
    for i in range(len(line)):
        if line[i]<=axins1_min<line[i+1]:
            t1=i
    for i in range(len(line)):
        if axins1_max<=line[i]:
            t2=i
            break
    for i in range(t1,(t2+1)):
        axins1.plot([line[i]]*16,"--",linewidth=0.5,color='r',alpha=0.7)
    for i in range(t1,t2):
        axins1.text(xzone[i],yzone[i],zone[i], fontproperties =font_set4)
        
    axins1.legend(loc="upper right",frameon=False,prop=font_set1)

#E轴    
    axins2=axins.twinx()
    e1_mean=[all_value1['E1_1_mean']]
    e2_mean=[all_value1['E1_2_mean']]
    e3_mean=[all_value1['E_2_mean']]
    e4_mean=[all_value1['E_3_mean']]
    e1_max=[all_value1['E1_1_max']]
    e2_max=[all_value1['E1_2_max']]
    e3_max=[all_value1['E_2_max']]
    e4_max=[all_value1['E_3_max']]
    e1_min=[all_value1['E1_1_min']]
    e2_min=[all_value1['E1_2_min']]
    e3_min=[all_value1['E_2_min']]
    e4_min=[all_value1['E_3_min']]
    y=[panduan(e1_mean),panduan(e2_mean),panduan(e3_mean),panduan(e4_mean)]
    y=tuli(y)
    plotsca_E(axins2,e1_mean,x1,y[0])
    plotsca_E(axins2,e1_max,x1,0)
    plotsca_E(axins2,e1_min,x1,0)
    plotsca_E(axins2,e2_mean,x2,y[1])
    plotsca_E(axins2,e2_max,x2,0)
    plotsca_E(axins2,e2_min,x2,0)
    plotsca_E(axins2,e3_mean,x3,y[2])
    plotsca_E(axins2,e3_max,x3,0)
    plotsca_E(axins2,e3_min,x3,0)
    plotsca_E(axins2,e4_mean,x4,y[3])
    plotsca_E(axins2,e4_max,x4,0)
    plotsca_E(axins2,e4_min,x4,0)
    axins2.set_ylabel('E',fontproperties =font_set1)
    
    E_min=[all_value1['E1_1_min'],
            all_value1['E1_2_min'],
            all_value1['E_2_min'],
            all_value1['E_3_min']]
    axins2_min=[]
    for i in range(0,len(E_min)):
        if E_min[i]!=999999:
            axins2_min.append(E_min[i])
    axins2_min=min(axins2_min)    
    E_max=[all_value1['E1_1_max'],
            all_value1['E1_2_max'],
            all_value1['E_2_max'],
            all_value1['E_3_max']]
    axins2_max=[]
    for i in range(0,len(E_max)):
        if E_max[i]!=999999:
            axins2_max.append(E_max[i])
    axins2_max=max(axins2_max)
 #设置E轴的刻度 
    ax_min=math.ceil(axins2_min)-5
    ax_max=math.ceil(axins2_max)+5
    step=math.ceil((ax_max-ax_min)/5)
    l=math.ceil(ax_max/step)
    axins2_ymax=l*(step)
    axins2_ymin=axins2_ymax-6*(step)
    axins2.set_ylim(axins2_ymin,axins2_ymax)
    ymajorLocator = MultipleLocator(step)
    ymajorFormatter = FormatStrFormatter('%d')
    axins2.yaxis.set_major_locator(ymajorLocator)
    axins2.yaxis.set_major_formatter(ymajorFormatter)
    axins2.spines["right"].set_position(("axes", 1.11))
    axins2.legend(bbox_to_anchor=(0.985,0.93),frameon=False,prop=font_set1)
    return axins,axins1,axins2    

import os #读取某个文件夹下的全部csv，其中os.path.splitext()函数将路径拆分为文件名+扩展名
def file_name(file_dir):  
    L=[]
    name=[]
    for root, dirs, files in os.walk(file_dir): 
        for file in files: 
            if os.path.splitext(file)[1] == '.csv': 
                L.append(os.path.join(root, file))
                name.append(file)
    return L,name 

#目前只支持寒温带落叶针叶林区域
import xlrd
import sqlite3
def get_bianhao(a):
    a="'"+a+"'"
    conn=sqlite3.connect('mrsoft.db')
    cursor=conn.cursor()
    cursor.execute('select name from zhibei where bh='+a)
    result1=cursor.fetchone()
    cursor.close()
    conn.close()
    return result1[0]


# In[44]:


# 构建回归模型图示
def figure_drawing(x,y,z,alpha,**kwargs):
    all_value = data_process(x,y,alpha)
#     plt.rcParams['ytick.direction'] = 'out'
#     fig, ax = plt.subplots(figsize = (12,8))
#     ax.xaxis.set_ticks_position('bottom')
#     ax.spines['bottom'].set_position(('data', 0))
#     ax.yaxis.set_ticks_position('left')
#     ax.spines['left'].set_position(('data', 0))
#     ax.spines['right'].set_color('none')
#     ax.spines['top'].set_color('none')
    
    fig, ax = plt.subplots(figsize = (17,13))
    fig.patch.set_facecolor('white')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data', 0))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data', 0))
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    ax.grid(ls='--',linewidth=0.4)
    

    ylimit_down = min(y)
    ylimit_up = max(y)
    
#分区回归
#第一区
    x1 = all_value['tb1']
    y1 = all_value['E1']  
#     if all_value['n1']==0:
#         print('第一区为空')
#第二区
    x2 =all_value['tb2']
    y2 =all_value['E2'] 
#第三区
    x3 =all_value['tb3']
    y3 =all_value['E3']
    
    x4 =all_value['tb4']
    y4 =all_value['E4']
#二三区一起做回归
    x234=x2+x3+x4
    y234=y2+y3+y4
#分类
    if z==1:
        xy=np.vstack((x,y))
        xy=np.stack(xy,axis=1)
        xy=np.array(xy)
    
        xy1=[]
    elif z==2:
        xy=np.vstack((x1,y1))
        xy=np.stack(xy,axis=1)
        xy=np.array(xy)
    
        xy1=np.vstack((x234,y234))
        xy1=np.stack(xy1,axis=1)
        xy1=np.array(xy1)

    xy2=[]
    xy3=[]
    xy4=[]

    xy2=np.array(xy2)
    xy3=np.array(xy3)
    xy4=np.array(xy4)
    A = ['1','2','3','4','5']
    B = [xy,xy1,xy2,xy3,xy4]
    z=dict(zip(A,B))
    spotValue=['g','g','y','steelblue','sandybrown']
    lineValue=['darkred','darkred','gold','deepskyblue','orangered']
    qunluo=['类型3','类型3','类型3','类型4','类型5']
    
    diyu=''
    spot_color=int(str5_4)
    spot_color1=int(str5_2_1)
    
    if spot_color==1:
        spotValue[0]=spotValue[1]='r'
        qunluo[0]=qunluo[1]=diyu+'类型1'
    elif spot_color==2:
        spotValue[0]=spotValue[1]='darkorchid'
        qunluo[0]=qunluo[1]=diyu+'类型2'
    elif spot_color==3:
        spotValue[0]=spotValue[1]='g'
        qunluo[0]=qunluo[1]=diyu+'类型3'
    elif spot_color==4:
        spotValue[0]=spotValue[1]='b'
        qunluo[0]=qunluo[1]=diyu+'类型4'
    elif spot_color==5:
        spotValue[0]=spotValue[1]='fuchsia'
        qunluo[0]=qunluo[1]=diyu+'类型5'
    elif spot_color==6:
        spotValue[0]=spotValue[1]='limegreen'
        qunluo[0]=qunluo[1]=diyu+'类型6'
    elif spot_color==7:
        spotValue[0]=spotValue[1]='lightseagreen'
        qunluo[0]=qunluo[1]=diyu+'类型7'
    elif spot_color==8:
        spotValue[0]=spotValue[1]='chocolate'
        qunluo[0]=qunluo[1]=diyu+'类型8'
    elif spot_color==9:
        spotValue[0]=spotValue[1]='deepskyblue'
        qunluo[0]=qunluo[1]=diyu+'类型9'
    elif spot_color==10:
        spotValue[0]=spotValue[1]='y'
        qunluo[0]=qunluo[1]=diyu+'类型10'
    elif spot_color==11:
        spotValue[0]=spotValue[1]='#990033'
        qunluo[0]=qunluo[1]=diyu+'类型11'
    elif spot_color==12:
        spotValue[0]=spotValue[1]='#FF9966'
        qunluo[0]=qunluo[1]=diyu+'类型12'
    elif spot_color==13:
        spotValue[0]=spotValue[1]='#996699'
        qunluo[0]=qunluo[1]=diyu+'类型13'
    elif spot_color==14:
        spotValue[0]=spotValue[1]='#FF99CC'
        qunluo[0]=qunluo[1]=diyu+'类型14'
    elif spot_color==15:
        spotValue[0]=spotValue[1]='#999900'
        qunluo[0]=qunluo[1]=diyu+'类型15'
    elif spot_color==16:
        spotValue[0]=spotValue[1]='#50616d'
        qunluo[0]=qunluo[1]=diyu+'类型16' 
    elif spot_color==17:
        spotValue[0]=spotValue[1]='maroon'
        qunluo[0]=qunluo[1]=diyu+'类型17'
    elif spot_color==18:
        spotValue[0]=spotValue[1]='bisque'
        qunluo[0]=qunluo[1]=diyu+'类型18'
    elif spot_color==19:
        spotValue[0]=spotValue[1]='darkblue'
        qunluo[0]=qunluo[1]=diyu+'类型19'
    elif spot_color1==0 and spot_color ==0 :
        spotValue[0]=spotValue[1]='y'
        qunluo[0]=qunluo[1]='温度交错带'   
    elif spot_color1==1 and spot_color ==0 :
        spotValue[0]=spotValue[1]='darkorchid'
        qunluo[0]=qunluo[1]='高山极地带'     
    elif spot_color1==2 and spot_color ==0 :
        spotValue[0]=spotValue[1]='fuchsia'
        qunluo[0]=qunluo[1]='苔原带'
    elif spot_color1==3 and spot_color ==0 :
        spotValue[0]=spotValue[1]='b'
        qunluo[0]=qunluo[1]='寒温带' 
    elif spot_color1==4 and spot_color ==0 :
        spotValue[0]=spotValue[1]='mediumaquamarine'
        qunluo[0]=qunluo[1]='中温带'     
    elif spot_color1==5 and spot_color ==0 :
        spotValue[0]=spotValue[1]='limegreen'
        qunluo[0]=qunluo[1]='暖温带'
    elif spot_color1==6 and spot_color ==0 :
        spotValue[0]=spotValue[1]='darkorange'
        qunluo[0]=qunluo[1]='亚热带' 
    elif spot_color1==7 and spot_color ==0 :
        spotValue[0]=spotValue[1]='r'
        qunluo[0]=qunluo[1]='热带' 
    
    
    if len(xy)==0:
        j=1
    else:
        j=0
    
    regression=[]
    for i in range(0,2):       
        coo=[]
        coo=z[A[i]]
        if   0<len(coo)<=2:
            if i==j:
                ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])
            else:
                ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])
            regression.append(['/','/','/'])
        elif len(coo)>2:
            poly_val,test_val, process_val = polyfit_one(coo[:,0], coo[:,1],alpha)
            if poly_val[0]==999999:
                if len(coo)<=100:
                    if i==j:
                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])
                    else:
                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])   
                else:
                    if i==j:
                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])
                    else:
                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)])
            elif poly_val[0]==99999999:
                    poly_text1 = "$TB = %.2f$" % (poly_val[1])
                    X_test = np.ones(1000000)*poly_val[1]
                    Y_test = np.linspace(-60,60, 1000000)
                    plt.plot( X_test, Y_test, '-',color=lineValue[i%len(lineValue)],label=poly_text1, linewidth=1)
                    if len(coo)<=100:
                        if i==j:
                            ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])
                        else:
                            ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])   
                    else:
                        if i==j:
                            ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])
                        else:
                            ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)])
            else:
                if 0 <= poly_val[0]< 99999999:
                    poly_text1 = "$E = %.2f *TB  + %.2f$（$R^2 = %.2f$）" % (poly_val[1], poly_val[0],test_val['R2'])#加$会使字体倾斜加粗
                else:
                    poly_text1 = "$E = %.2f *TB  + %.2f$（$R^2 = %.2f$）" % (poly_val[1], poly_val[0],test_val['R2'])
        
                if len(coo)<=100:
                    if i==j:
                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])
                    else:
                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])   
                else:
                    if i==j:
                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])
                    else:
                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)])
                X_test = np.linspace(0,math.ceil(max(x))+6, 1000000)
                Y_test = X_test* poly_val[1]+poly_val[0]
                plt.plot( X_test, Y_test, '-',color=lineValue[i%len(lineValue)],label=poly_text1, linewidth=1)

            regression.append([test_val['R2'],test_val['Pvalue'],poly_text1])
        
    poly_text2 = '分区界限'
    ax.plot(np.linspace(0, 30, 1000000), 5.893*1.8099*np.linspace(0, 30, 1000000), '--k', label=poly_text2)
    ax.plot(np.linspace(0, 30, 1000000), -5.893*1.8099*np.linspace(0, 30, 1000000), '--k')
    plt.axhline(0, color='k')#第四区线，p=1/2pe
    
    poly_text3='中心点位置'
#     ax.scatter(all_value['TB_mean'],all_value['E_mean'],s=30,c='r',marker = 'o',label=poly_text3)  
    
    xlabel = 'TB (℃)'
    ylabel = 'E'
    ax.set_xlabel(xlabel,fontproperties =font_set)
    ax.set_ylabel(ylabel,fontproperties =font_set)
    
   
    
    xmajorLocator = MultipleLocator(1)
    xmajorFormatter = FormatStrFormatter('%d')
    ymajorLocator = MultipleLocator(50)
    ymajorFormatter = FormatStrFormatter('%1.1f')
    ax.xaxis.set_major_locator(xmajorLocator)
    ax.xaxis.set_major_formatter(xmajorFormatter)
    ax.yaxis.set_major_locator(ymajorLocator)
    ax.yaxis.set_major_formatter(ymajorFormatter)
    ax.set_xlim(0,30)
    ax.set_ylim(-500,700)
    
    
    plt.text(29,350,'Ⅰ,Ⅱ', fontproperties =font_set)
    plt.text(29.3,110,'Ⅲ', fontproperties =font_set)
    plt.text(29.3,-190,'Ⅳ', fontproperties =font_set)

    
    
    title = kwargs['title']
    ax.set_title(title,fontproperties =font_set)
#     plt.setp(ax.xaxis.get_majorticklabels(), rotation=-20)#坐标系数字的倾斜程度
    
    legend = ax.legend(loc="lower left",prop=font_set1)
    legend_f = legend.get_frame()
    legend_f.set_facecolor("white")
#     xy1[]=0
#左上角画条形折线图
    all_value0=data_process(np.array(x),np.array(y),alpha)
    all_value1=data_process(np.array(x),np.array(y),alpha)
    
    if spot_color==0 and (spot_color1==0 or spot_color1 ==1):
        plt.text(4.6,390,qunluo[0]+'('+str('%.2f'%(len(x)/total*100))+'%)', fontproperties =font_set1)
    else:
        plt.text(4.8,390,qunluo[0]+'('+str('%.2f'%(len(x)/total*100))+'%)', fontproperties =font_set1)
    plt.text(4.8,370,'('+str('%.2f'%all_value1['TB_mean'])+','+str('%.2f'%all_value1['E_mean'])+')',fontproperties =font_set1)

#         plt.text(4.8,390,qunluo[0]+'('+str('%.2f'%(len(x)/total*100))+'%)', fontproperties =font_set1)
#         plt.text(4.8,370,'('+str('%.2f'%all_value1['TB_mean'])+','+str('%.2f'%all_value1['E_mean'])+')',fontproperties =font_set1)    
    barline1(all_value0,all_value1,fig)  
    legend = ax.legend(loc="lower left",prop=font_set1)
    legend_f = legend.get_frame()
    legend_f.set_facecolor("white")
    return figure_drawing,regression

def judge_p(p):
    try:
        if p>0.05:
            Pvalue='P>0.05'
        elif 0.001<p<=0.05:
            Pvalue='0.001<P<=0.05'
        elif p<=0.001:
            Pvalue='P<=0.001'
    except TypeError:
        Pvalue=p
    return Pvalue


# In[45]:


# coding: utf-8
headers=['name','value','说明书名字','说明书群系编号','总样本点数','分区后总样本点数','温度带','区域','小地域','类型',
         '总体回归方程','R方','P值','P值范围',
         '分类型回归方程1','R方','P值','P值范围',
         '分类型回归方程2','R方','P值','P值范围',
        'TB_max','TB_min','TB_mean','TB_std',
        'E_max','E_min','E_mean','E_std',
        'p_max','p_min','p_mean','p_std',
        'pe_max','pe_min','pe_mean','pe_std',
        'dem_max','dem_min','dem_mean','dem_std',
        'tp_year_max','tp_year_min','tp_year_mean','tp_year_std']
rows=[]
aaa = '230b余甘子、糙叶水锦树灌丛'
bbb = r'311_余甘子、糙叶水锦树灌丛'
aaa = aaa.split('_')[0]
bbb = bbb.replace('jia','+')
bbb += '_'
for i in range(len(aaa)):
    if ord(aaa[i]) >10000:
        e = i
        break
bbb += aaa[e:]
bbb += '_' +    aaa[:e]     
List=[bbb]
print(List)
csvpath=r'E:\tutu\csv'#运行csv所在的文件夹，该程序运行的是该文件夹下的所有的csv文件
sp = r'E:\tutu\123' #目标路径
csv_number=0
for i in List:
    str1=i.split('_')[0]#value
    str2=i.split('_')[1]#name
    str3=i.split('_')[2]#说明书上的名字
    str4=i.split('_')[3]#说明书上的群系编号
    #csv名称
    str8=str4+ '_' +str3+'_各类型信息统计'
    str6=0
    #str6='椴、槭林'#输出二级分类的csv名
  
    if __name__ == "__main__":
        
#         csvpath=r'C:\Users\DellYY\Desktop\切图斑csv\612'#运行csv所在的文件夹，该程序运行的是该文件夹下的所有的csv文件
        L,name=file_name(csvpath)
        path=csvpath+r'\总体拟合'
        if not os.path.exists(path):
            os.mkdir(path)
        else:
            print('总体拟合文件夹已创建')
        for str5 in name:
            L=[]
            print('\n当前csv:'+str5)
            if str5[:-4] == str8:
                continue

####################植被小区的名字，改改改#################
            str5_1=str5.split('.')[1]#大地域编号
            str5_1='地域'+str5_1  #地域1
#########################################################

            str5_2_1=str5.split('.')[0]#温度带 5
            str5_3=str5.split('.')[2]#地域 0
            str5_4=str5.split('.')[3].split('_')[0]#子类型 5
                
            temprList = ['温度交错带','高山极地带', '苔原带', '寒温带', '中温带', '暖温带', '亚热带', '热带']
            
            if str5_4 == '0':
                if str5_1=='':
                    str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]#输出图片名
                else:
                    str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'_'+str5_1#输出图片名
            else:
                if str5_1=='':
                    if str5_3=='0':
                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'_'+'类型'+str5_4#输出图片名
                    else:
                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'-'+str5_3+'_'+'类型'+str5_4#输出图片名
                else:
                    if str5_3=='0':
                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+ '_'+str5_1+'_'+'类型'+str5_4#输出图片名
                    else:
                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+ '_'+str5_1+'-'+str5_3+'_'+'类型'+str5_4#输出图片名
            
            tmix_list=[]
            tmix_str=''
            if str5_2_1 == '0':
                tmix=str5.split('_')[1][:-4]
                tmix_list=tmix.split('.')
                for TL in range(len(tmix_list)):
                    tmix_list[TL]  = temprList[int(tmix_list[TL])]
                tmix_str='-'.join(tmix_list)
                str7=str7.replace('温度',tmix_str)
                
                sph = sp +'\\温度带' + '\\' +str5_2_1 + '_' + temprList[int(str5_2_1)] + '\\'  + tmix + '_' + tmix_str+'交错带' +  '\\不压点有序度图'
                if not os.path.isdir(sph):
                    os.mkdir(sph)
                sph = sp +'\\温度带' + '\\' +str5_2_1 + '_' + temprList[int(str5_2_1)] + '\\' + tmix + '_' + tmix_str+'交错带' + '\\不压点有序度图\\%s.png'
            else:
                sph = sp +'\\温度带' + '\\' +str5_2_1 + '_' + temprList[int(str5_2_1)] + '\\' + '\\不压点有序度图'
                if not os.path.isdir(sph):
                    os.mkdir(sph)
                sph = sp +'\\温度带' + '\\' +str5_2_1 + '_' + temprList[int(str5_2_1)] + '\\'   + '\\不压点有序度图\\%s.png'
            print(sph)
            x, y,check,p_pe,p1_pe1,p2_pe2 ,p3_pe3,p4_pe4,p5_pe5,p6_pe6,p7_pe7,p8_pe8,p9_pe9,p10_pe10,p11_pe11,p12_pe12,total,p,pe,dem,tp_year= read_xy(csvpath+'/%s'%str5)

            #检查data数据导出时命名是否正确
            check_value = check[0]
            if check_value != int(str1):
                    print('value值和data数据内不一致')
            all_value = data_process(x,y,0.05)
            print('总样本点数：%d'%all_value['n'])
            print('分区后的总样本点数：%d'%all_value['n_check'])
            #分类型拟合
            fig_opt = {'title': ('$%s$'+ ' '+u'%s'+str7.replace(str4+'_'+str3,'').replace('_',' '))%(str4,str3)}   
            figure_drawing,regression2 = figure_drawing(x, y, 2,0.05, **fig_opt)
            fig_save_address1=csvpath.replace('\\','/')+'/%s.png'
            plt.savefig(sph%str7,dpi = 300,bbox_inches='tight')
            #总体拟合
            figure_drawing1,regression1 = figure_drawing(x, y, 1,0.05, **fig_opt)    
            fig_save_address2=path.replace('\\','/')+'/%s.png'  
            plt.savefig(fig_save_address2%(str7),dpi = 300,bbox_inches='tight')
            plt.close()
            if len(regression2)==1:
                regression2.append(['/','/','/'])
            csv_number+=all_value['n_check']
            L=[str2,str1,str3,str4,total,all_value['n_check'],temprList[int(str5_2_1)].replace('温度',tmix_str),
               str5_1[2:],str5_3,str5_4,
               regression1[0][2].replace('$','').split('(')[0],regression1[0][0],regression1[0][1],judge_p(regression1[0][1]),
               regression2[0][2].replace('$','').split('(')[0],regression2[0][0],regression2[0][1],judge_p(regression2[0][1]),
               regression2[1][2].replace('$','').split('(')[0],regression2[1][0],regression2[1][1],judge_p(regression2[1][1]),
              all_value['TB_max'],all_value['TB_min'],all_value['TB_mean'],all_value['TB_std'],
              all_value['E_max'],all_value['E_min'],all_value['E_mean'],all_value['E_std'],
              all_value['p_max'],all_value['p_min'],all_value['p_mean'],all_value['p_std'],
              all_value['pe_max'],all_value['pe_min'],all_value['pe_mean'],all_value['pe_std'],
              all_value['DEM_max'],all_value['DEM_min'],all_value['DEM_mean'],all_value['DEM_std'],
              all_value['tp_year_max'],all_value['tp_year_min'],all_value['tp_year_mean'],all_value['tp_year_std']]
            rows.append(L)

if csv_number==total:
    print('\n各csv点数之和与该群系总点数相等')
else:
    print('\n各csv点数之和与该群系总点数不相等,请检查:\n1.该群系的所有csv是否同时跑了\n2.是否有漏点情况')

print('\n开始生成信息统计csv\n--------分割线--------')
csv_save_address=csvpath.replace('\\','/')+'/%s.csv'
with open(csv_save_address%str8,'a',newline='') as f1:
    f1_csv = csv.writer(f1)
    f1_csv.writerow(headers)
    f1_csv.writerows(rows)
print(aaa[:e] + '_' +  aaa[e:])

